package me.hgj.jetpackmvvm.ledun.ui.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import me.hgj.jetpackmvvm.ledun.R

//自定义 seekbar
class CustomSeekBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr){

   private var progress = 0
    var maxProgress = 100
    var thumbPosition: Float = 0f // 滑块的当前位置
    private var isDragging = false
    var thumbDrawable: Drawable?=null
    var backThumbDrawable: Drawable?=null
    // 文本绘制属性
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLACK
        // 文字颜色
        textSize = 24f // 文字大小
        textAlign = Paint.Align.CENTER
    }
    interface SeekBarChangeListener {
        fun onProgressChanged(seekBar: me.hgj.jetpackmvvm.ledun.ui.view.CustomSeekBar, progress: Int, fromUser: Boolean)
        fun onStopTrackingTouch(seekBar: me.hgj.jetpackmvvm.ledun.ui.view.CustomSeekBar,isAdjust:Boolean)
    }

    private var listener: SeekBarChangeListener? = null

    // 设置监听器的方法
    fun setOnSeekBarChangeListener(listener: SeekBarChangeListener) {
        this.listener = listener
    }




    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomSeekBar)
        val seekBarColor = typedArray.getString(R.styleable.CustomSeekBar_seekBarColor)
//        val startColor = typedArray.getColor(R.styleable.CustomSeekBar_startColor, 0xFF3F51B5.toInt())
//        val endColor = typedArray.getColor(R.styleable.CustomSeekBar_endColor, 0xFFFFC107.toInt())

        thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb, null)
        val intSeekBar= seekBarColor!!.toInt()
        when(intSeekBar){
            0->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb, null)

            }
            1->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb1, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb1, null)
            }
            2->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb2, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb2, null)
            }
            3->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb3, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb3, null)
            }
            4->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb4, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb4, null)
            }
            5->{
                backThumbDrawable= context.resources.getDrawable(R.drawable.back_thumb5, null)
                thumbDrawable = context.resources.getDrawable(R.drawable.rect_thumb5, null)
            }
        }


    }

//    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
//        super.onSizeChanged(w, h, oldw, oldh)
//        // Update the LinearGradient shader if the size of the view changes
//        (paint.shader as? LinearGradient)?.setLocalMatrix(null)
//    }
//
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
       //30dp
        val desiredHeight = resources.getDimensionPixelSize(R.dimen.seekbar_height) // 固定的高度 控制整个区域的大小
       val width = MeasureSpec.getSize(widthMeasureSpec)
      setMeasuredDimension(width, desiredHeight)

    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // Draw the gradient background

        // 绘制渐变背景
        backThumbDrawable!!.setBounds(0, 65, width, height-65) //控制绘制背景区域的大小
        backThumbDrawable!!.draw(canvas)

    if (thumbDrawable != null) {
        // 根据thumbPosition确定滑块位置，并绘制
//        val thumbLeft = thumbPosition - thumbDrawable!!.intrinsicWidth / 2f
//        val thumbTop = (height - thumbDrawable!!.intrinsicHeight) / 2f
        thumbDrawable!!.setBounds(thumbPosition.toInt(), (height - thumbDrawable!!.intrinsicHeight) / 2f.toInt(),
         thumbPosition.toInt()+ thumbDrawable!!.intrinsicWidth.toInt(),
            (height - thumbDrawable!!.intrinsicHeight) / 2f.toInt()+thumbDrawable!!.intrinsicHeight)
        thumbDrawable!!.draw(canvas)

        val text = progress.toString()
        val textWidth = textPaint.measureText(text)
        canvas.drawText(
            text,
            thumbPosition+thumbDrawable!!.intrinsicWidth/2f,
            (height - thumbDrawable!!.intrinsicHeight) / 2f-5,
            textPaint
        )
    }

    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x

        when (event.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
//                // 更新滑块位置，确保滑块在SeekBar范围内
//                // 更新滑块位置，确保滑块在SeekBar范围内
//                thumbPosition = x.coerceIn( 0f, width.toFloat())
//                // 根据滑块位置计算进度
//                progress = ((thumbPosition / width) * maxProgress).toInt()
//                // 重绘视图以反映滑块位置变化
//                invalidate()
                isDragging=true
                val realWidth= width - (thumbDrawable?.intrinsicWidth?.toFloat() ?: 0f)
                thumbPosition = x.coerceIn(0f,realWidth) //这个是为了限定上下极限值
                // 更新进度值
                progress = ((thumbPosition / (width - thumbDrawable?.intrinsicWidth?.toFloat()!! ?: 1f)) * maxProgress).toInt()
                // 确保进度可以达到100 如果相等那么值 x最大值 就是100
                progress = if (thumbPosition == width - (thumbDrawable?.intrinsicWidth?.toFloat() ?: 0f)) 100 else progress

                //引入一个全局变量
                //此时就是没有剩余值了
//                setProgress(progress, true)
                listener?.onProgressChanged(this, progress, true)

                invalidate()


            }
            MotionEvent.ACTION_UP -> {
                isDragging = false
                //拖动结束设置一个监听器.
                listener?.onStopTrackingTouch(this,true)
                // Handle the final progress value here, e.g., notify a listener
            }
        }
        return true
    }


//  更具progress设置对应滑块的位置
fun setProgress(newProgress: Int, fromUser: Boolean) {
       //
    val realWidth= width - (thumbDrawable?.intrinsicWidth?.toFloat() ?: 0f)
    progress=newProgress  //更新进度
    progress.coerceIn(0,100)
    thumbPosition=(progress/100f)*realWidth//确定当前的位置
    thumbPosition.coerceIn(0f,realWidth)
    //刷新绘制

    invalidate()
    listener?.onStopTrackingTouch(this,false)
    }

    //获取到当前的进度。
    fun getProgress():Int{
        return progress
    }

    companion object {
        // Declare the custom attributes for the CustomSeekBar
        @Retention(AnnotationRetention.SOURCE)
        @Target(AnnotationTarget.CLASS)
        annotation class CustomSeekBar
    }
}
    // 可以添加getter和setter方法来外部访问和修改progress和maxProgress